<?php declare(strict_types=1);

namespace app\admin\service;

use think\facade\Config;
use think\facade\Db;

class SystemLogService
{
    /**
     * 当前实例
     * @var object
     */
    private static $instance;

    /**
     * 表前缀
     * @var string
     */
    protected $tablePrefix;

    /**
     * 表后缀
     * @var string
     */
    protected $tableSuffix;

    /**
     * 表名
     * @var string
     */
    protected $tableName;

    protected function __construct()
    {
        $this->tablePrefix = Config::get('database.connections.mysql.prefix');
        $this->tableSuffix = date("Ym", time());
        $this->tableName = "{$this->tablePrefix}admin_log";

        return $this;
    }

    /**
     * 获取实例对象
     * @return object
     */
    public static function instance(){
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }

        return self::$instance;
    }

    /**
     * 保存数据
     * @return void
     */
    public function save($data){
        $this->checkTable();
        Db::startTrans();
        try {
            Db::table($this->tableName)->insert($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollbakc();
            return $e->getMessage();
        }

        return true;
    }

    /**
     * 检测表是否存在
     * @return bool
     */
    public function checkTable(){
        $check = Db::query("show tables like '{$this->tableName}'");
        if (!$check) {
            $sql = $this->getCreateSql();
            Db::excute($sql);
        }

        return true;
    }

    /**
     * 生成SQL
     * @return bool
     */
    protected function getCreateSql(){
        $sql = <<<EOT
CREATE TABLE `{$this->tableName}` (
    `id` bigint(20) unsigned NOT NULL AUTO COMMENT COMMET 'ID',
    `admin_user` varchar(50) NOT NULL DEFAULT '' COMMENT '管理员',
    `route` varchar(5000) NOT NULL DEFAULT '' COMMENT '请求路由',
    `method` varchar(10) NOT NULL DEFAULT '' COMMENT '请求方法',
    `request_data` varchar(5000) NOT NULL DEFAULT '' COMMENT '操作内容（简单描述）',
    `ip` varchar(100) NOT NULL DEFAULT '' COMMENT 'ip',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='后台操作日志表 - {$this->tableSuffix}';
EOT;

    return $sql;
    }

}